<template>
	<view class="page">
		<view class="header">
			<view class="header-1"><u-icon name="arrow-leftward" color="323233" size="18" @click="toGoBack()"></u-icon>
			</view>
			<view class="header-2">
				<image src="/static/logo.png"></image>
				教育培训系统
			</view>
			<view class="header-3"></view>
		</view>
		<view class="content">
			<!-- 视频 -->
			<template v-if="fileType == 'videos'">
				<view class="video">
					<video id="myVideo" :src="src" :controls="controls" :autoplay="autoplay" :initial-time="currentTime" v-if="src" @ended="videoEnded"
						@timeupdate="onPlayerTimeupdate($event)" @loadedmetadata="onVideoLoaded" style="width: 100%; height: 211px;"></video>
				</view>
				<view class="videoContent">
					<view class="title">{{ info.name }}</view>
				<!-- 	<view :class="['tag', info.temsCourseStudyInfo.process >= 100 ? 'tag-over' : '']" v-if="info.temsCourseStudyInfo">
						{{ info.temsCourseStudyInfo.process >= 100 ? '已学习' : '待学习' }}
					</view> -->
					<template v-if="type == 1">
						<view :class="['tag', enabledMark == 30 ? 'tag-over' : '']" v-if="enabledMark">
							<template v-if="enabledMark == 10">待自测</template>
							<template v-else-if="enabledMark == 20">学习中</template>
							<template v-if="enabledMark == 30">已完成</template>
						</view>
						<view class="tag" v-else>待自测</view>
					</template>
					<template v-else-if="type == 2">
						<view :class="['tag', process >= 100 ? 'tag-over' : '']">
							{{ process >= 100 ? '已学习' : '待学习' }}
						</view> 
					</template>
				</view>
				<view v-if="type == 1" class="submitButton">
					<!-- 已经完成的不需要锁了 -->
					<template v-if="info.temsCourseChapterList[0].process == 100">
					  <u-button class="uButton" @click="submitItem()">开始考试</u-button>
					</template>
					<template v-else>
						<u-button :class="['uButton', isPlayed ? '' : 'disabled']" @click="isPlayed ?  submitItem() : ''">开始考试</u-button>
					</template>
				</view>
				<view v-else-if="type == 2" class="submitButton">
					<u-button class="uButton" @click="submitCloseItem()">关闭</u-button>
				</view>
			</template>
			<!-- 图片 -->
			<template v-else-if="fileType == 'image'">
				<view class="videoContent">
					<view class="title">{{ info.name }}</view>
				<!-- 	<view :class="['tag', info.temsCourseStudyInfo.process >= 100 ? 'tag-over' : '']" v-if="info.temsCourseStudyInfo">
						{{ info.temsCourseStudyInfo.process >= 100 ? '已学习' : '待学习' }}
					</view> -->
					<template v-if="type == 1">
						<view :class="['tag', enabledMark == 30 ? 'tag-over' : '']" v-if="enabledMark">
							<template v-if="enabledMark == 10">待自测</template>
							<template v-else-if="enabledMark == 20">学习中</template>
							<template v-if="enabledMark == 30">已完成</template>
						</view>
						<view class="tag" v-else>待自测</view>
					</template>
					<template v-else-if="type == 2">
						<view :class="['tag', process >= 100 ? 'tag-over' : '']">
							{{ process >= 100 ? '已学习' : '待学习' }}
						</view> 
					</template>
				</view>
				<view @click="openImgAttachment" style="padding: 10px 16px; color: #2265EE; text-decoration: underline;">
				   <image :src="src" style="width: 100%" mode="widthFix"></image>
				</view>
				<view v-if="type == 1" class="submitButton">
					<u-button class="uButton" @click="submitItem()">开始考试</u-button>
				</view>
				<view v-else-if="type == 2" class="submitButton">
					<u-button class="uButton" @click="submitCloseItem()">关闭</u-button>
				</view>
			</template>
			<!-- word、pdf等文件 -->
			<template v-else-if="fileType == 'file' || fileType == 'pdf'">
				<view class="videoContent">
					<view class="title">{{ info.name }}</view>
					<!-- <view :class="['tag', info.temsCourseStudyInfo.process >= 100 ? 'tag-over' : '']" v-if="info.temsCourseStudyInfo">
						{{ info.temsCourseStudyInfo.process >= 100 ? '已学习' : '待学习' }}
					</view> -->
					<template v-if="type == 1">
						<view :class="['tag', enabledMark == 30 ? 'tag-over' : '']" v-if="enabledMark">
							<template v-if="enabledMark == 10">待自测</template>
							<template v-else-if="enabledMark == 20">学习中</template>
							<template v-if="enabledMark == 30">已完成</template>
						</view>
						<view class="tag" v-else>待自测</view>
					</template>
					<template v-else-if="type == 2">
						<view :class="['tag', process >= 100 ? 'tag-over' : '']">
							{{ process >= 100 ? '已学习' : '待学习' }}
						</view> 
					</template>
				</view>
				<view @click="openAttachment" style="padding: 10px 16px; color: #2265EE; text-decoration: underline;">
				    附件： {{ currentName }}
				</view>
				<view v-if="type == 1" class="submitButton">
					<u-button class="uButton" @click="submitItem()">开始考试</u-button>
				</view>
				<view v-else-if="type == 2" class="submitButton">
					<u-button class="uButton" @click="submitCloseItem()">关闭</u-button>
				</view>
			</template>
		</view>
	</view>
</template>

<script>
	import {
		getTemsCourseDetail, PreviewFile, TemsCourseStudy
	} from "@/api/index";
	export default {
		data() {
			return {
				process: 0,
				enabledMark: null,
				type: null,
				id: null,
				src: '',
				controls: false,
				autoplay: false,
				info: {
					temsCourseStudyInfo: {
						process: null
					}
				},
				fileImage: this.$globalSetting.fileImage,
				isPlayed: false,
				fileUrl: this.$globalSetting.fileImage,
				fileType: null,
				videos: ['mp4','mp3'],
				sufix: ['xlsx', 'xls', 'docx', 'doc', 'ppt', 'pptx'],
				imgs: ['jpg', 'jpeg', 'png', 'gif'],
				pdf: ['pdf'],
				currentName: '',
				currentTime: 0,
				videoDuration: 0, // 添加视频总时长
				videoContext: null // 添加视频上下文

			}
		},
		onLoad(e) {
			this.id = e.id;
			this.process = e.process;
			this.enabledMark = e.enabledMark;
			this.type = e.type;
			if (this.process >= 100) {
				this.controls = true;
			}
			this.initData();
		},
		onReady() {
			// 创建视频上下文
			this.videoContext = uni.createVideoContext('myVideo', this);
		},
		methods: {
			openAttachment() {
				if (!this.info.temsCourseChapterList || !this.info.temsCourseChapterList[0].url) {
					this.showSuccess("附件链接无效", "none");
					return;
				}
				this.loadUrls(this.info.temsCourseChapterList[0]);
			},
			// 图片
			openImgAttachment() {
				wx.previewImage({
					current: '', // 当前显示图片的http链接
					urls: [this.src] // 需要预览的图片http链接列表[]像这种其实就是数组
				});
			},
			initData() {
				getTemsCourseDetail(this.id).then(res => {
					this.info = res.data;
					let name = this.currentName = res.data.temsCourseChapterList[0].name;
					const fileExtension = name.split('.').pop().toLowerCase();
					const isVideos = this.videos.includes(fileExtension);
					const isSufix = this.sufix.includes(fileExtension);
					const isPdf = this.pdf.includes(fileExtension);
					const isImgs = this.imgs.includes(fileExtension);
					if (isVideos) {
						this.fileType = 'videos';
						this.src = res.data.temsCourseChapterList ? this.fileUrl + res.data.temsCourseChapterList[0].url : '';
						// 根据学习进度设置初始播放时间
						if (this.info.temsCourseChapterList && this.info.temsCourseChapterList[0].process < 100) {
							// 这里先设置一个默认值，实际时间需要在视频加载后计算
							this.currentTime = 0;
						}
					} else if (isSufix) {
						this.fileType = 'file';
					} else if (isPdf) {
						this.fileType = 'pdf';
					} else if (isImgs) {
						this.fileType = 'image';
					}
					if (!isVideos) {
						setTimeout(() => {
						  this.studyInterval(100)
						}, 50000);
					}
				})
				.catch(err => {
					this.showSuccess(err || '系统繁忙，请稍后再试！', 'none');
				});
			},
			// 视频元数据加载完成
			onVideoLoaded(e) {
				console.log('视频元数据加载完成，时长:', e.detail.duration);
				this.videoDuration = e.detail.duration;
				
				// 根据学习进度比例计算播放时间点
				if (this.info.temsCourseChapterList && this.info.temsCourseChapterList[0].process < 100) {
					const progress = this.info.temsCourseChapterList[0].process;
					const targetTime = (progress / 100) * this.videoDuration;
					
					console.log(`学习进度: ${progress}%, 计算播放时间: ${targetTime}秒`);
					
					// 如果计算出的时间大于10秒，使用seek方法跳转
					if (targetTime > 10) {
						this.currentTime = targetTime;
						
						// 延迟执行确保视频已准备好
						setTimeout(() => {
							if (this.videoContext) {
								this.videoContext.seek(targetTime);
								console.log('视频已跳转到:', targetTime, '秒');
							}
						}, 800);
						
						// 显示提示
						setTimeout(() => {
							this.showRestorePrompt(targetTime, progress);
						}, 1500);
					}
				}
			},
			// 显示恢复提示
			showRestorePrompt(targetTime, progress) {
				uni.showModal({
					title: '提示',
					content: `检测到您已学习 ${progress}%，是否从 ${this.formatTime(targetTime)} 继续学习？`,
					confirmText: '继续学习',
					cancelText: '重新开始',
					success: (res) => {
						if (res.cancel) {
							// 用户选择重新开始
							if (this.videoContext) {
								this.videoContext.seek(0);
								setTimeout(() => {
									this.videoContext.play(); // 重新开始也要播放
								}, 300);
							}
							this.currentTime = 0;
							// 重置学习进度为0
							this.resetStudyProgress();
						}
					}
				});
			},
			// 格式化时间显示
			formatTime(seconds) {
				const mins = Math.floor(seconds / 60);
				const secs = Math.floor(seconds % 60);
				return `${mins}分${secs}秒`;
			},
			// 重置学习进度
			resetStudyProgress() {
				if (this.info.temsCourseChapterList && this.info.temsCourseChapterList.length > 0) {
					TemsCourseStudy(this.info.temsCourseChapterList[0].id, 0).then((res) => {
						this.info = res.data;
						console.log('学习进度已重置为0%');
					});
				}
			},
			loadUrls(data) { 
				let file = JSON.parse(data.fileJson)
                let fileName = file.url.split('/').pop();
				const query = {
					fileVersionId: file.fileVersionId,
					secondFilePath: file.secondFilePath,
					fileName: fileName,  // fileId
					fileDownloadUrl: file.url
				};
				PreviewFile(query).then(res => {
					let srcs = this.src = res.data
					uni.navigateTo({
						url: `/pages/learnCenter/webview?url=${encodeURIComponent(srcs)}`
					});
				})
			},
			toGoBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			submitItem() {
				if (!this.isPlayed && this.enabledMark != 30) {
					this.showSuccess("请先观看完视频","none");
					return;
				}
				if (!this.info.homeExam) {
					this.showSuccess("暂无考试","none");
					return;
				}
				// 跳转到查看考试详情页面
				uni.navigateTo({
					url: `/pages/examinationInterface/examinationInterface?id=${this.info.homeExam}`
				});
			},
			submitCloseItem() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 当播放到末尾时触发 ended 事件
			videoEnded() {
				this.isPlayed = true;
			},
			studyInterval(e) {
			  if (this.info.temsCourseChapterList && this.info.temsCourseChapterList.length > 0) {
				TemsCourseStudy(this.info.temsCourseChapterList[0].id, Number(e)).then((res) => {
				  this.info = res.data
				})
			  }
			},
			// 视频播放时，时间的回调
			onPlayerTimeupdate(e) {
				let process = (e.detail.currentTime / e.detail.duration * 100).toFixed(2)
				if (Math.floor(process % 5) === 0) {
					this.studyInterval(process)
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	
	.uButton {
		width: 100%;
		height: 44px;
		background-color: #2265EE;
		border-radius: 22px;
		color: #fff;
	}

	.uButton.disabled {
	    color: #8B8A92;
	    background-color: #F0EFF4;
	}
	
	.submitButton {
		padding: 16px;
		margin-top: 20px;
		position: fixed;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
	}
	
	.page {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		position: relative;
		background: #F6F8FC;

		.header {
			width: 100%;
			height: 88rpx;
			line-height: 88rpx;
			background-color: #fff;
			display: flex;

			.header-1 {
				margin: 30rpx 0 0 38rpx;
				justify-content: center;
				align-items: center;

			}

			.header-2 {
				flex: 10;
				text-align: center;
				display: flex;
				justify-content: center;
				align-items: center;

				image {
					width: 48rpx;
					height: 48rpx;
					margin-right: 16rpx;
				}
			}

			.header-3 {
				flex: 1;
			}
		}

		.content {
			display: flex;
			flex-direction: column;

			.videoContent {
				margin-top: 24px;
				padding: 0 0 0 16px;

				.title {
					font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
					font-weight: 500;
					font-size: 16px;
					color: #323233;
					line-height: 24px;
					text-align: left;
					font-style: normal;
				}

				.tag {
					width: 44px;
					height: 20px;
					background: #FF7E00;
					border-radius: 2px;
					display: flex;
					justify-content: center;
					align-items: center;
					font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
					font-weight: 400;
					font-size: 12px;
					color: #FFFFFF;
					line-height: 16px;
					text-align: left;
					font-style: normal;
				}

				.tag.tag-over {
					background: #19be6b;
				}

			}


		}


	}
</style>